import { IComponent } from "./sys";
import { ComponentArgs } from "../filesystem";

/**
 * Button控件
 */
export class Button extends IComponent {

    /**
     * Button控件内部包含的a标签
     */
    private innerA: HTMLAnchorElement;

    /**
     *如果填充了url,则此按钮可以提供下载的功能
     */
    public url?: string;

    /**
     *按钮的名称 
     */
    public textContent: string;

    /**
     * 按钮的配置参数
     */
    public data: ButtonArgs;

    /**
     * 点击事件
     */
    public onclick: (e: Event, btn: Button) => void;

    public constructor(args: ButtonArgs) {
        super(args);
        this._init(args)
    }

    /**
     * 设置Button的url
     * @param url 
     */
    public setUrl(url: string) {
        this.url = url;
        this.innerA.href = url;
    }

    private _init(args: ButtonArgs) {
        this.data = args;
        (args.id !== null && args.id != undefined) ? this.id = args.id : this.id = null;
        args.classList === null ? this.classList = ["primary"] : this.classList = args.classList;
        if (args.url !== null && args.url !== undefined) {
            this.url = args.url;
        } else {
            this.url = "#";
        }
        this.textContent = args.textContent;
        this.domBase = this._createDomBase(args);
        this.onclick = args.onclick || null;
        //bind将上下文设置为this
        this.domBase.onclick = this.doClick.bind(this)
    }

    protected doClick(e: Event, btn: Button) {
        /**
         * TODO:根据enabled和disabled来决定是不是要传递事件
         */
        this.onclick(e, this);
    }

    protected _createDomBase(args: ButtonArgs): HTMLElement {
        /**
         * 复合控件,重写父类方法
         */
        if (args.domBase) {
            this.domBase = args.domBase;
            this.domParent = <HTMLElement>this.domBase.parentNode || null;
        } else {
            this.domBase = document.createElement("div");
        }
        this.domBase.setAttribute("class", this.classList.join(" "));
        if (args.id !== null && args.id !== undefined) {
            this.domBase.id = args.id;
        }
        this.domBase.szobject = this;
        let a: HTMLAnchorElement = document.createElement("a");
        a.href = this.url;
        a.textContent = this.textContent;
        this.domBase.appendChild(a);
        this.innerA = a;
        return this.domBase;
    }
}

/**
 * 创建button时的接口参数
 */
export interface ButtonArgs extends ComponentArgs {

    /***
     * 如果提供了url,则是下载类型的按钮,可以不传入onclick
     */
    url?: string;

    /**
     * 样式列表
     */
    classList?: string[];

    /**
     * 按钮展示文字
     */
    textContent: string;

    /**
     * 
     * @param e 按钮点击事件
     */
    onclick(e: Event, btn: Button): void;
}